package com.sg.zwfw.handllers;

import com.sg.zwfw.utils.Signature;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class TifSignatureInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TifSignatureInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = ((HandlerMethod) handler);

        Method method = handlerMethod.getMethod();


        String time = request.getHeader("x-tif-timestamp");
        long ltime = Long.parseLong(time);


        String nonce = request.getHeader("x-tif-nonce");
        String uid = request.getHeader("x-tif-uid");
        String uinfo = request.getHeader("x-tif-uinfo");
        String ext = request.getHeader("x-tif-ext");

        String signature = request.getHeader("x-tif-signature");
        String paasid = request.getHeader("x-tif-paasId");


        String token = "";
        String sn = time + token + nonce + time;
        String validSignature = Signature.toSHA256(sn);
        if (!validSignature.equalsIgnoreCase(signature)) {
            logger.error("wrong x_tif_signature expect:{}, actual:{}", validSignature, signature);
            throw new Exception();
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
